package com.yuandian.management.controller;

import com.yuandian.api.management.entity.ConfAgentIp;
import com.yuandian.api.management.entity.ConfAgentStatusInfo;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.bpm.common.log.annotation.SysLog;
import com.yuandian.bpm.common.security.util.SecurityUtils;
import com.yuandian.management.service.ConfAgentStatusInfoService;
import com.yuandian.management.service.IAgentIpService;
import com.yuandian.management.utils.IpUtils;
import com.yuandian.management.vo.*;
import com.yuandian.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Agent状态信息表-Controller
 * @author zfsn
 * @date 2023-4-14
 */
@Slf4j
@Api(tags = "自监控配置-agent状态监控")
@RestController
@RequestMapping("/modules/monitor/agent")
public class ConfAgentStatusInfoController {

	@Autowired
	private ConfAgentStatusInfoService confAgentStatusInfoService;

	@Autowired
	private IAgentIpService agentIpService;

	/**
	 * 新增数据
	 * @return 通用返回对象
	 */
	@ApiOperation(value = "新增数据", notes = "新增数据")
	@SysLog("新增Agent状态信息表数据")
	@PostMapping
	public R save(@RequestBody AgentStatusInfoDto[] agents, HttpServletRequest request) {
		String method = request.getHeader("method");
		String module = request.getHeader("module");
		String timestamp = request.getHeader("timestamp");

		log.debug("method: {}, module:{}, timestamp: {}", method, module, timestamp);

		if (StringUtils.isEmpty(method) || !"com.yuandian.probe.agent.save".equals(method)) {
			log.error("method为空或者非法参数: {}", method);
			return R.failed("method为空或者非法参数");
		}
		if (StringUtils.isEmpty(timestamp)) {
			log.error("timestamp为空: {}", timestamp);
			return R.failed("timestamp为空");
		}
		if (StringUtils.isEmpty(module) || !"BPM_PROBE".equals(module)) {
			log.error("module为空或者非法参数: {}", module);
			return R.failed("module为空或者非法参数");
		} else {
			// 3、 根据request请求获取请求IP与module参数关联查询t_module_management、t_module_type，
			// 如果不存在数据，则拒绝处理此请求，返回错误码-1，错误提示：非法请求
			List<String> proIpList = confAgentStatusInfoService.getModuleManagement("BPM_PROBE");
			String probeIp = IpUtils.getIpAddr(request);
			log.debug(probeIp);
			if (CollectionUtils.isEmpty(proIpList) || !proIpList.contains(probeIp)) {
				log.error("接口/modules/probe/agent/save，从t_module_management里面找不到请求的ip: {}", probeIp);
				return R.failed("在t_module_management里面找不到请求的ip:" + probeIp);
			}
		}

		confAgentStatusInfoService.handleAgentStatusInfo(agents, request);
		return R.ok();
	}

	/**
	 * 统计agent状态个数
	 *
	 * @return
	 */
	@GetMapping("/getAgentCount")
	@ApiOperation(value = "Agent总览(今天)", notes = "Agent总览(今天)")
	public R getAgentCount() {
		return confAgentStatusInfoService.getAgentCount();
	}

	/**
	 * 查询当天的信息，按ip分组统计，参数是状态
	 *
	 * @param ap
	 * @return
	 */
	@PostMapping("/getAgentTable")
	@ApiOperation(value = "Agent概况", notes = "Agent概况")
	public R getAgentTable(@RequestBody AgentStatusInfoParams ap) {
		return confAgentStatusInfoService.queryListGroupByIpAndAgentStatus(ap);
	}




	/**
	 * 查询agnet列表，按ip和状态查询
	 *
	 * @return
	 */
	@ApiOperation(value = "Agent异常状态监控-详情列表", notes = "Agent异常状态监控-详情列表")
	@PostMapping("/getAgentShowList")
	public R getAgentShowList(@RequestBody AgentStatusInfoParams ap) {
		return confAgentStatusInfoService.queryListByIpAndAgentStatus(ap);
	}



	/**
	 * 更新当天的不参加top展示的断采信息
	 *
	 * @param agentIp
	 * @return
	 */
	@GetMapping("/updateCollectTopStatusByIp")
	@ApiOperation(value = "更新当天的不参加top展示的断采信息", notes = "更新当天的不参加top展示的断采信息")
	public R updateCollectTopStatusByIp(String agentIp) {
		int num = confAgentStatusInfoService.updateCollectTopStatusByIp(agentIp);
		return num > 0 ? R.ok() : R.failed();
	}

	/**
	 * 前端操作，根据ip过滤掉当前的异常top排名
	 *
	 * @param agentIp
	 * @return
	 */
	@GetMapping("/updateWrongTopStatusByIp")
	@ApiOperation(value = "根据ip过滤掉当前的异常top排名", notes = "根据ip过滤掉当前的异常top排名")
	public R updateWrongTopStatusByIp(String agentIp) {
		int num = confAgentStatusInfoService.updateWrongTopStatusByIp(agentIp);
		return num > 0 ? R.ok() : R.failed();
	}


	/**
	 * 根据ip查询历史启动时间
	 *
	 * @param agentIp
	 * @return
	 */
	@GetMapping("/getHistoryRebootTime")
	@ApiOperation(value = "根据ip查询历史启动时间", notes = "根据ip查询历史启动时间")
	public R getHistoryRebootTime(String agentIp) {
		List<ConfAgentStatusInfo> list = confAgentStatusInfoService.rebootHistoryTime(agentIp);
		return R.ok(list);
	}

	/**
	 * top断采信息
	 *
	 * @return
	 */
	@GetMapping("/getBreakTop")
	@ApiOperation(value = "断采次数TOP5", notes = "断采次数TOP5")
	public R getBreakTop() {
		return confAgentStatusInfoService.getBreakTop();
	}

	/**
	 * top异常信息
	 *
	 * @return
	 */
	@GetMapping("/getWrongTop")
	@ApiOperation(value = "异常次数TOP5", notes = "异常次数TOP5")
	public R getWrongTop() {
		return confAgentStatusInfoService.getWrongTop();
	}

	/**
	 * 更新当天的不参加top展示的断采信息
	 *
	 * @param ap
	 * @return
	 */
	@PostMapping("/getAgentDetail")
	@ApiOperation(value = "更新当天的不参加top展示的断采信息", notes = "更新当天的不参加top展示的断采信息")
	public R getAgentDetail(@RequestBody AgentStatusInfoPojo ap) {
		ConfAgentStatusInfo vo = confAgentStatusInfoService.getAgentDetail(ap);
		return R.ok(vo);
	}

	/**
	 * 丢包率历史曲线图(agentIp,startTime,endTime)
	 *
	 * @param params
	 * @return
	 */
	@PostMapping("/lostHistoryLine")
	@ApiOperation(value = "历史曲线图-丢包率", notes = "历史曲线图-丢包率")
	public R lostHistoryLine(@RequestBody AgentStatusInfoParams params) {
		return confAgentStatusInfoService.lostHistoryLine(params);
	}

	/**
	 * 流量历史曲线图(agentIp,startTime,endTime)
	 *
	 * @param params
	 * @return
	 */
	@ApiOperation(value = "历史曲线图-流量历史曲线图", notes = "历史曲线图-流量历史曲线图")
	@PostMapping("/speedHistoryLine")
	public R speedHistoryLine(@RequestBody AgentStatusInfoParams params) {
		return confAgentStatusInfoService.speedHistoryLine(params);
	}


	/**
	 * 根据条件查询
	 *
	 * @param searchKey
	 * @return
	 */
	@GetMapping({"/getAgentIpList/{searchKey}", "/getAgentIpList"})
	@ApiOperation(value = "Agent管理-查询", notes = "Agent管理-查询")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "searchKey", value = "查询条件", paramType = "path", required = false, dataType = "String"),
	})
	public R getAgentIpList(@PathVariable(value = "searchKey", required = false) String searchKey) {
		if (StringUtils.isBlank(searchKey)) {
			searchKey = null;
		}

		List<ConfAgentIp>  list = confAgentStatusInfoService.queryList(searchKey);
		return R.ok(list);
	}

	/**
	 * 更新agentip 别名和主机名和磁盘分区过滤
	 *
	 * @param agentIp
	 * @return
	 */
	@PostMapping("/updateAgentByIp")
	@ApiOperation(value = "Agent管理-修改", notes = "Agent管理-修改")
	public R updateAgentByIp(@RequestBody AgentIpPojo agentIp) {
		agentIp.setUpdateBy(SecurityUtils.getUser().getName());
		agentIp.setUpdateTime(new Date());
		int num = agentIpService.updateByIpSelective(agentIp);
		if (num == 0) {
			return R.failed(null,"更新失败！");
		}

		Map<String, AgentIpPojo> agentIpMap = AgentConfigManager.agentIpMap;
		AgentIpPojo po = agentIpMap.get(agentIp.getAgentIp());
		if (po != null) {
			po.setAliasName(agentIp.getAliasName());
			po.setRemoveDiskPartition(agentIp.getRemoveDiskPartition());
		}

		return R.ok();
	}

}
